package website.web;
import java.util.Map;

import com.amazonaws.services.dynamodb.model.AttributeValue;

import cloudjunit.*;
import dynamojunit.UserSessionTable;
import dynamojunit.WorkflowTable;

public class JarJunitSessionManager {
	public static String get_session_status(String session_id)
	{
		UserSessionTable session_table = new UserSessionTable(false);
		String wfid = session_table.getSessionCurrentWorkflowId(session_id);
		
		StringBuffer resp_buff = new StringBuffer();
		resp_buff.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
		resp_buff.append("<response>\n");
		resp_buff.append("<status>\n");
		
		if ((wfid == "")||(wfid.contains("RESET")))
		{
			//no workflow started
			resp_buff.append("NEW"+"\n");
			resp_buff.append("</status>\n");
			resp_buff.append("</response>\n");
			return resp_buff.toString();
		}
		
		WorkflowTable workflow_table = new WorkflowTable(false);
		if (!workflow_table.isWorkFlowIdExist(wfid))
		{
			//during init
			resp_buff.append(JunitWorkFlowState.INITIAL+"\n");
			resp_buff.append("</status>\n");
			resp_buff.append("</response>\n");
			return resp_buff.toString();
		}
		
		Map<String, AttributeValue> values_map = workflow_table.readWorkflowEntry(wfid);
		String status = workflow_table.readWorkFlowStatus(values_map);
		status = status.trim();
		resp_buff.append(status+"\n");
		resp_buff.append("</status>\n");
		
		System.out.println("get_session_status: current status is "+status);
		
		if (status == JunitWorkFlowState.INITIAL)
		{
			System.out.println("get_session_status: INITIAL");
		}
		else if (status == JunitWorkFlowState.ANALYZING)
		{
			System.out.println("get_session_status: ANALYZING");
		}
		else if (status.equalsIgnoreCase(JunitWorkFlowState.RUNNING) ||status.equalsIgnoreCase(JunitWorkFlowState.DONE))
		{
			System.out.println("get_session_status: RUNNING or DONE");
			
			String total_num_of_tests = workflow_table.readWorkFlowTotalNumberOfTests(values_map);
			
			String total_num_of_passed_tests = workflow_table.readNumberOfPassedTests(values_map);
			String total_num_of_failed_tests = workflow_table.readNumberOfFailedTests(values_map);
			
			resp_buff.append("<numTotal>");
			resp_buff.append(total_num_of_tests);
			resp_buff.append("</numTotal>");
			resp_buff.append("<numOK>");
			resp_buff.append(total_num_of_passed_tests);
			resp_buff.append("</numOK>");
			resp_buff.append("<numFail>");
			resp_buff.append(total_num_of_failed_tests);
			resp_buff.append("</numFail>");
		}
		else if (status == JunitWorkFlowState.ERROR)
		{

		}
		
		resp_buff.append("</response>\n");
		return resp_buff.toString();
	}
	
	public static void init_session(String session_id)
	{
		System.out.println("init_session");
		UserSessionTable session_table = new UserSessionTable(false);
		session_table.updateSessionWorkFlow(session_id, "RESET");
		System.out.println("ok");
	}
}